package netty.v3.serializer;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.ByteBufAllocator;

public class PacketCodeC<T> {

    private static int MAGIC_NUMBER = 0x174;

    private Serializer<T> serializer =  new JSONSerializer<>();

    /**
     * 获取到请求数据后反序列化
     * */
    public  T decode(ByteBuf byteBuf){

        //忽略头文件
        byteBuf.skipBytes(4);

        //获取请求类型
        int reqType = byteBuf.readInt();

        //获取版本号
        byte version = byteBuf.readByte();

        //获取本次请求数据长度
        int length = byteBuf.readInt();

        //获取数据
        byte[] bytes = new byte[length];
        byteBuf.readBytes(bytes);


        T packet = null;

        switch (Command.get(reqType)){
            case LOGIN_COMMAND :

                packet = serializer.deserializer(LoginReqPacket.class, bytes);
                break;

            default:
                break;
        }

        return packet;
    }

    /**
     * 数据传输之前序列化
     * */
    public ByteBuf encode(Packet packet, ByteBufAllocator bufAllocator){

        ByteBuf byteBuf = bufAllocator.ioBuffer();

        //写入头文字
        byteBuf.writeInt(MAGIC_NUMBER);

        //写入请求类型
        byteBuf.writeInt(packet.getCommand());

        //写入版本号
        byteBuf.writeByte(packet.version);

        byte[] bytes = serializer.serializer(packet);
        //写入数据长度
        byteBuf.writeInt(bytes.length);

        //写入数据
        byteBuf.writeBytes(bytes);

        return byteBuf;
    }
}
